package dk.rhok.server;

import java.io.IOException;
import java.util.Random;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import dk.rhok.model.ShelterAssessmentImpl;

@WebServlet("/Ass")

public class XMLToModel extends HttpServlet{
	private ShelterAssessmentImpl shelterEntry;
	private Document dom;
	
	public void doPost (HttpServletRequest req, HttpServletResponse resp) {
	
		try {			
			SAXBuilder builder = new SAXBuilder();
			dom = builder.build(req.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
			dom = null;			
		} catch (JDOMException e) {
			e.printStackTrace();
			dom = null;			
		}
		
		if (dom != null) {
		Element root = dom.getRootElement();
		//dom.getRootElement()
		
			long date =  Long.parseLong(root.getChildText("time"));
			Element location = root.getChild("location");
			double lat = Double.parseDouble(location.getAttributeValue("lat"));
			double lon = Double.parseDouble(location.getAttributeValue("loc"));
			int households = Integer.parseInt(root.getChildText("households"));
			int people = Integer.parseInt(root.getChildText("people"));
			//Not implemented in datamodel
			String remark = root.getChildText("remark");
			String site = location.getText();
			
			shelterEntry = new ShelterAssessmentImpl(date, lat, lon, households, people, new Random().nextInt(2000000000), new Random().nextInt(2000000000), new Random().nextInt(2000000000), new Random().nextInt(2000000000), new Random().nextInt(2000000000));
			doMagic(shelterEntry);
		} else {
			System.out.println("XMLToModel - document creation failed.... do something...");
		}
		
	}
	
	private void doMagic(ShelterAssessmentImpl ass) {
		String foo = "alibasta";
	}
}